/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-11-28 13:20:25
 * 天凉好个秋
 */
import { Context } from "koa";
import fs from "fs";
import response from "../../utils/response";
import path from "path";
import { randomStr } from "../../utils/util";
import config from "../config";

class Upload {
  async uploadImg(ctx: Context) {
    const file = ctx.request.files?.file;
    try {
      if (file) {
        const fileType = new Set([
          "image/jpg",
          "image/png",
          "image/gif",
          "image/jpeg",
        ]);
        // @ts-ignore
        if (!fileType.has(file.type)) return response.error(ctx, `不支持的图片格式: ${file.type}`);
        // @ts-ignore
        const reader = fs.createReadStream(file.path);
        // @ts-ignore
        const ext = path.extname(file.name);
        // @ts-ignore
        const filePath = `/imgs/${randomStr(32)}${ext}`;
        const writer = fs.createWriteStream("static" + filePath);
        reader.pipe(writer);
        response.success(ctx, {
          url: `http://127.0.0.1:${config.server.port}${filePath}`,
        });
      } else {
        response.error(ctx, "请选择图片");
      }
    } catch (error) {
      response.error(ctx, error);
    }
  }
}

export default new Upload();
